/**
 * ### 本单元用于展示RPC接口的编写与注册
 * 
 * 可根据需求进行修改、删除
 * 
 */

import { userEntrySchema, loginUserEntrySchema, type IRspUser, createErrorMessage, ErrorMessage, type IReqLoginUser, type IReqCreateUser, type IRspLoginInfo } from "@packages/shared";
import User from "../models/user.model";
import { registerRpcMethod, type RpcMethod } from "./core";
import assert from 'assert'
import jwt from 'jsonwebtoken'
import env from "../utils/env";
import { infoLog } from "../utils/log";

/**
 * ### 注册新用户
 * 
 * @param param -  IReqCreateUser
 * @returns - IRspUser
 */
const registerNewUser = async (param: IReqCreateUser): Promise<IRspLoginInfo> => {

    const userExist = await User.findOne({ username: param.username })
    assert(!userExist, createErrorMessage(ErrorMessage.Exits, '用户'))

    const user = (await User.insertOne(param)).toJSON()
    const { password, __v, ...rspUser } = user

    return {
        user: rspUser as unknown as IRspUser,
        token: jwt.sign({ _id: rspUser._id }, env.JWT_SECRET)
    }
}

const loginUser = async (param: IReqLoginUser): Promise<IRspLoginInfo> => {
    const user = await User.findOne({ username: param.username }, '_id username age phone nickName gender').select('password')

    infoLog(user)

    assert(user, createErrorMessage(ErrorMessage.NotExits, '用户'))

    assert.ok(user.password === param.password, createErrorMessage(ErrorMessage.Mismatch, '密码'))
    const { password, __v, ...rspUser } = user.toJSON()

    return {
        user: rspUser as unknown as IRspUser,
        token: jwt.sign({ _id: rspUser._id }, env.JWT_SECRET)
    }
}


registerRpcMethod([
    {
        handler: registerNewUser as RpcMethod,
        auth: false,
        validator: userEntrySchema,
        paramType: 'IReqCreateUser',
        returnType: 'IRspUser'
    },
    {
        handler: loginUser as RpcMethod,
        auth: false,
        validator: loginUserEntrySchema,
        paramType: 'IReqLoginUser',
        returnType: 'IRspLoginInfo'
    },
])